<template>
  <div class="code-editor--panel">
    <div class="toolbar">
      <span class="toolbar-label">连接:</span>
      <el-select size="small" v-model="context.environ.connection" filterable placeholder="选择连接"
                 @change="onConnectionChange">
        <el-option v-for="connection in connections" :key="connection.label" :label="connection.label"
                   :value="connection.label" :title="`${connection.host}:${connection.port}`"></el-option>
      </el-select>
      <el-divider direction="vertical"></el-divider>
      <span class="toolbar-label">数据库:</span>
      <el-select size="small" v-model="context.environ.database" filterable placeholder="选择数据库"
                 v-loading="isDatabaseLoading">
        <el-option v-for="database in databases" :key="database" :label="database.name"
                   :value="database.name"></el-option>
      </el-select>
      <el-divider direction="vertical"></el-divider>
      <el-link size="small" @click="onFormat()">
        <el-icon>
          <Finished />
        </el-icon>
        格式化
      </el-link>
      <el-divider direction="vertical"></el-divider>
      <el-link size="small" @click="onExecute()">
        <el-icon>
          <VideoPlay />
        </el-icon>
        执行
      </el-link>
      <el-divider direction="vertical"></el-divider>
      <label for="open-file" class="open-file-icon">
        <el-link size="small">
          <el-icon>
            <Document />
          </el-icon>
          运行文件
        </el-link>
      </label>
      <el-divider direction="vertical"></el-divider>
      <input type="file" style="display:none;" @change="onFileChange" id="open-file" />
    </div>
    <div class="code-editor">
      <cm :code="context.environ.statement" ref="editor" @run="onExecute" />
    </div>
  </div>
</template>

<script setup>
import { Document, Finished, VideoPlay } from '@element-plus/icons-vue'
import Cm from './Cm.vue'
</script>
<script>
import { mapGetters } from 'vuex'
import bus from '@/assets/scripts/bus'
import apis from '@/assets/apis'

export default {
  name: 'CodeEditor',
  inject: {
    context: 'context'
  },
  mounted() {
    this.loadDatabases()
  },
  data() {
    return {
      databases: [],
      isDatabaseLoading: false,
      editor: null
    }
  },
  methods: {
    onFormat() {
      this.$refs.editor.format()
    },
    onExecute() {
      if (!this.context.environ.connection) {
        // ElMessage.info('请选择连接')
        return
      }
      if (!this.context.environ.database) {
        // ElMessage.info('请选择数据库')
        return
      }
      const code = this.$refs.editor.getSelected() || this.$refs.editor.getValue()
      // this.context.environ.statement = code;
      if (!code) {
        // ElMessage.info('请输入 SQL')
        return
      }
      this.$emit('query', code)
    },
    onFileChange(e) {
      const files = e.target.files
      if (!files.length) {
        return
      }
      const reader = new FileReader()
      reader.onload = e => {
        const content = e.target.result
        bus.emit('file-loaded', {
          filename: files[0].name,
          connection: this.context.environ.connection,
          database: this.context.environ.database,
          statement: content
        })
      }
      reader.readAsText(files[0])
    },
    onConnectionChange() {
      this.loadDatabases()
    },
    loadDatabases() {
      this.databases = []
      const connectionName = this.context.environ.connection
      if (!connectionName) {
        return
      }
      const connection = this.connections.filter(connection => connection.label === connectionName)[0]
      if (!connection) {
        return
      }
      if (connection.databases && connection.databases.length) {
        this.databases = connection.databases
        return
      }

      this.isDatabaseLoading = true
      this.$store.commit('updateGlobalMsg', '正在加载信息...')
      apis.dbm.connection.connect(connection).then(data => {
        const databaseList = data[0].data.map(item => ({
          name: item[0],
          opened: false,
          expanded: false,
          connection
        }))
        databaseList.sort((a, b) => a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1)
        this.$store.commit('updateGlobalMsg', '加载完成')
        this.$store.commit('updateDatabaseList', {
          list: databaseList,
          label: connection.label
        })
        this.databases = databaseList
      }).catch(e => {
        this.$store.commit('updateGlobalMsg', `错误： ${e.message}`)
        ElMessage.error(e.message)
      }).finally(() => {
        this.isDatabaseLoading = false
      })
    }
  },
  beforeUnmount() {
  },
  computed: {
    ...mapGetters({
      activeInfo: 'activeInfo',
      connections: 'allConnections'
    })
  }
}
</script>

<style lang="less" scoped>
.code-editor--panel {
  position: relative;
  display: block;
  height: 100%;
  padding: 34px 0 0 0;
  margin: 0;
  overflow: hidden;
  box-sizing: border-box;
}

.toolbar {
  position: absolute;
  top: 0;
  left: 0;
  padding: 2px 5px;
  width: 100%;
  height: 34px;
  background-color: #fcfcfc;
  border-bottom: 1px solid #eeeeee;
  box-sizing: border-box;
}

.toolbar-label {
  font-size: 12px;
  margin-right: 2px;
  color: #666666;
}

.code-editor {
  height: 100%;
  position: relative;
  cursor: text;
}

.toolbar-right {
  float: right;
}

.open-file-icon .el-icon {
  vertical-align: middle;
}
</style>
<style lang="less">
.el-table.el-table--small .el-table__cell {
  padding: 2px 0;
  --el-table-header-background-color: #fafafa;

  .cell {
    padding: 0 5px;
    color: #333333;
  }
}

.el-table__header {
  .el-table__cell {
    color: #333333;
    font-weight: normal;
  }
}
</style>
